package com.bruce.codeFactory.Thread;

import java.util.stream.Stream;

/**
 * @author luotuan
 * @Description  生产者消费者例子
 * @create 2019-02-19 21:36
 **/
public class ProduceConsumerDemo {
    private final Object lock = new Object();
    private int i = 0;
    private volatile boolean isProducted = false;

    public static void main(String[] args) {
        ProduceConsumerDemo demo = new ProduceConsumerDemo();
        Stream.of("ss1","ss2").forEach(n->
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    demo.produce();
                }
            }
        }.start());
        Stream.of("ss3","ss4").forEach(n->
                new Thread() {
                    @Override
                    public void run() {
                        while (true) {
                            demo.consumer();
                        }
                    }
                }.start());
    }

    public void produce() {
        synchronized (lock) {
            while (isProducted) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            i++;
            System.out.println("生产------>" + i);
            isProducted = true;
            lock.notifyAll();

        }
    }

    public void consumer() {
        synchronized (lock) {
            while (isProducted) {
                System.out.println("消费=====>" + i);
                isProducted = false;
                lock.notifyAll();
            }
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
